package com.itwn.email.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        // 创建模板对象
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 开启消息强制投递
        rabbitTemplate.setMandatory(true);
        // 消息到达交换机的确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("消息关联数据 = " + correlationData);
            // 消息到达交换机的确认
            if (ack) {
                System.out.println(" 消息已经到达交换机 ");
                // 更新消息表：status = 1
            } else {
                System.out.println(" 消息未到达交换机，原因为：" + cause);
                // 更新消息表：status = -1
            }
        });

        // 消息回退：消息无法从交换机路由到队列
        rabbitTemplate.setReturnsCallback(returned -> {
            System.out.println("消息内容：" + returned.getMessage());
            System.out.println("响应码：" + returned.getReplyCode());
            System.out.println("响应文本：" + returned.getReplyText());
            System.out.println("交换机：" + returned.getExchange());
            System.out.println("路由键：" + returned.getRoutingKey());
        });



        return rabbitTemplate;
    }
}
